import { type Ref} from "vue";
import { useUserStore } from "@/store/modules/userStore";
import { ElMessage } from "element-plus";
import { ROLE_ENUM } from "@/config";
import { router, ROUTER_HOME_PATH, ROUTER_LOGIN_PATH } from "@/router";
import { getLoginOut, getUserLogin } from "@/service/user/userService";

export function useLogin(userInfo: Ref<loginFormTypes>) {
  let { setUserConfig } = useUserStore();

  let { loading, run } = getUserLogin({
    userName: userInfo.value.userName,
    passWord: userInfo.value.passWord,
  });

  function useLoginHandle() {
    run(({ result }) => {
      if (!result) return;

      setUserConfig({
        token: result.token,
        userInfo: userInfo.value,
        role: ROLE_ENUM.SUPER,
      });

      ElMessage({
        message: "登录成功",
        type: "success",
      });

      router.push({
        path: ROUTER_HOME_PATH,
        replace: true,
      });
    });
  }

  return {
    loading,
    useLoginHandle,
  };
}

export function useLoginOut() {
  let { loading, run } = getLoginOut();

  let { deleteUserConfig } = useUserStore();

  function useLogoutHandle() {
    run(() => {
      ElMessage({
        message: "已登出",
        type: "success",
      });

      deleteUserConfig();

      router.push({
        path: ROUTER_LOGIN_PATH,
        replace: true,
      });
    });
  }

  return {
    loading,
    useLogoutHandle,
  };
}
